<script setup lang="ts">
import {
  AddRentOK,
  DelPark,
  DelRent,
  over,
  ParkList,
  RentFloor,
  RentList,
  UpLoadfile,
} from "@/apis/park";
import type { Datum, ParkListRow, ParkReu, RentData, RentFl } from "@/types/Park";
import { Upload } from "@element-plus/icons-vue";
import {
  ElMessage,
  ElMessageBox,
  type FormInstance,
  type FormRules,
  type UploadRawFile,
  type UploadRequestOptions,
  type UploadUserFile,
} from "element-plus";
import { id } from "element-plus/es/locales.mjs";
import { onMounted, ref, watch } from "vue";
import { useRouter } from "vue-router";
interface Row extends ParkListRow{
  rentList:Datum[]
}
const parkdata = ref<ParkReu>({
  page: 1,
  pageSize: 2,
  name: "",
});
const List = ref<Row[]>([]);
const total = ref<number>();
const parkList = async () => {
  const res = await ParkList(parkdata.value);
  // console.log('res',res);
  total.value = res.data.total;
  List.value=res.data.rows.map(item=>({
    ...item,
    rentList:[]
  }))
};
onMounted(() => {
  parkList();
});
const filetList = () => {
  parkdata.value.page = 1;
  parkList();
};
const router = useRouter();
const Edit = (id: string) => {
  router.push(`/exterprise/${id}`);
};

// 删除
const Del = async (id: string) => {
  const res = await DelPark(id);
  //  console.log('res',res);
  parkList();
};
// 添加合同
const RentRef = ref<FormInstance>();
const rentDialogVisible = ref(false);
const rentList = ref<RentFl[]>([]);
const AddRent = async (id: number) => {
  rentDialogVisible.value = true;
  const res = await RentFloor();
  rentList.value = res.data;
  Rentdata.value.enterpriseId = id;
};
const closeRent = () => {
  rentDialogVisible.value = false;
  RentRef.value?.resetFields();
  Rentdata.value = {
    buildingId: undefined,
    contractId: 0,
    contractUrl: "",
    endTime: "",
    enterpriseId: 0,
    startTime: "",
    type: 0,
  };
  TimeArr.value = [];
  fileList.value = [];
};
const fileList = ref<UploadUserFile[]>([]);
const Rentdata = ref<RentData>({
  buildingId: undefined,
  contractId: 0,
  contractUrl: "",
  endTime: "",
  enterpriseId: 0,
  startTime: "",
  type: 0,
});
const RentRules = ref<FormRules<RentData>>({
  buildingId: [
    { required: true, message: "请选择租赁楼宇", trigger: "change" },
  ],
  contractUrl: [
    { required: true, message: "请上传合同附件", trigger: "change" },
  ],
  endTime: [{ required: true, message: "请选择租赁结束日期", trigger: "blur" }],
});
// 时间选择器--限制日期选择
const disabledDate = (time: Date) => {
  // 时间小于当前时间的不让选
  return time.getTime() < Date.now() - 1000 * 60 * 60 * 24;
};
const TimeArr = ref([]);
watch(
  TimeArr,
  (val: string[]) => {
    if (val) {
      Rentdata.value.startTime = val[0];
      Rentdata.value.endTime = val[1];
    } else {
      Rentdata.value.startTime = "";
      Rentdata.value.endTime = "";
    }
  },
  { deep: true }
);
// 上传文件
const UploadFile = async (file: UploadRequestOptions) => {
  const formData = new FormData();
  formData.append("file", file.file);
  formData.append("type", "contract");
  const res = await UpLoadfile(formData);
  console.log("res", res);
  Rentdata.value.contractUrl = res.data.url;
  Rentdata.value.contractId = res.data.id;
  RentRef.value?.validateField("contractUrl");
  ElMessage.success("上传成功");
  return res.data.url;
};
const removeUpload = () => {
  Rentdata.value.contractUrl = "";
  Rentdata.value.contractId = undefined;
  RentRef.value?.validateField("contractUrl");
};
const beforeUpload = (file: UploadRawFile) => {
  if (file.size > 5 * 1024 * 1024) {
    ElMessage.error("文件大小不能超过5M");
    return false;
  } else {
    return true;
  }
};
const onsub = () => {
  RentRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const res = await AddRentOK(Rentdata.value);
      if (res.code === 10000) {
        ElMessage.success("租赁成功");
        closeRent();
      } else {
        ElMessage.error(res.msg);
      }
    }
  });
};
const OnSubRent = async () => {
  onsub();
};
// 展开行
const onExpandChange =async  (row: Row) => {
  // 获取企业的合同列表
  const res = await RentList(row.id)
  console.log('当前行被展开', res)
  // 把请求回来的数据，直接保存到当前行的企业信息中
  row.rentList = res.data
};
const Over=(row:Datum)=>{
  ElMessageBox.confirm("当前操作不可逆，确定吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // 删除
   await over(row.id)
   row.status=3
   ElMessage.success('删除成功')
  }).catch(()=>{})
}
// 删除合同
const Delrent=(son:Datum,father:Row)=>{
  ElMessageBox.confirm("确定要删除吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    // 删除
      await DelRent(son.id)
      father.rentList=father.rentList.filter((item:Datum)=>item.id!==son.id)
      ElMessage.success('删除成功')

  }).catch(()=>{})
}
</script>
<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="parkdata.name"
      />
      <el-button type="primary" @click="filetList">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterprise')"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="List" @expand-change="onExpandChange" row-key="id">
        <!-- 新增：展开部分 -->
        <el-table-column type="expand">
          <template #default="{row}">
            <el-table :data="row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="{row}">
                  <!-- 合同的租赁状态0待生效1生效中2已到期3已退租 -->
                  <el-tag
                    v-if="row.status === 0"
                    type="warning"
                    >待生效</el-tag
                  >
                  <el-tag v-if="row.status === 1" type="success">生效中</el-tag>
                  <el-tag v-if="row.status === 2" type="info">已到期</el-tag>
                 <el-tag v-if="row.status === 3" type="danger">已退租</el-tag>



                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="{row:Row}">
                  <el-button size="small" type="text" :disabled="row.status!==3" >续租</el-button>
                  <el-button size="small" type="text" @click="Over(Row)" :disabled="row.status===3">退租</el-button>
                  <el-button size="small" @click="Delrent(Row,row)" type="text" :disabled="row.status!==3">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column prop="name" label="企业名称" width="320" />
        <el-table-column prop="contact" label="联系人" />
        <el-table-column prop="contactNumber" label="联系电话" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button size="small" text type="primary" @click="AddRent(row.id)"
              >添加合同</el-button
            >
            <el-button size="small" text type="primary" @click="$router.push(`/exterpriseDetail/${row.id}`)">查看</el-button>
            <el-button size="small" text type="primary" @click="Edit(row.id)"
              >编辑</el-button
            >
            <el-button size="small" text type="primary" @click="Del(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="total"
        :page-sizes="[2, 3, 4, 5]"
        layout="total,sizes, prev, pager, next,jumper"
        v-model:current-page="parkdata.page"
        v-model:page-size="parkdata.pageSize"
        @change="parkList"
      />
    </div>
    <el-dialog
      v-model="rentDialogVisible"
      title="添加合同"
      @close="closeRent"
      width="580px"
    >
      <el-form
        label-position="top"
        ref="RentRef"
        :rules="RentRules"
        :model="Rentdata"
        style="margin: 10px 50px"
      >
        <el-form-item label="租赁楼宇" prop="buildingId">
          <el-select
            placeholder="请选择租赁的楼宇"
            v-model="Rentdata.buildingId"
          >
            <el-option
              v-for="item in rentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="租赁起止日期" prop="endTime">
          <el-date-picker
            v-model="TimeArr"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
          />
        </el-form-item>
        <el-form-item label="租赁合同 " prop="contractUrl">
          <el-upload
            class="upload-demo"
            action=""
            accept=".doc, .pdf"
            :http-request="UploadFile"
            :limit="3"
            v-model:file-list="fileList"
            :before-upload="beforeUpload"
            :on-remove="removeUpload"
          >
            <el-button type="primary" :icon="Upload">上传合同</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不得超过5M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeRent">取消</el-button>
        <el-button type="primary" @click="OnSubRent">确定</el-button>
      </template>
      {{ Rentdata }}
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
